import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 4个参数类型都在hadoop-common包中
 * 参数1，输入数据的偏移量
 * 参数2，输入数据
 * 参数3，输出数据的key
 * 参数4，输出数据的value
 */
public class HelloWorldMapper extends Mapper<LongWritable, Text, Text, IntWritable> {

    @Override
    protected void map(LongWritable key, Text value, final Context context) throws IOException, InterruptedException {
        //简单模拟分词
        String[] words = value.toString().split(" ");
        Map<String, Integer> map = new HashMap<>();

        //统计词计数
        Arrays.asList(words).forEach(word -> {
            if (map.get(word) != null) {
                map.put(word, map.get(word) + 1);
            } else {
                map.put(word, 1);
            }
        });

        System.out.println(map);
        //输出计算后的map到上下文中
        map.forEach((s, integer) -> {
            try {
                context.write(new Text(s), new IntWritable(integer));
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

    }
}
